<script setup>
import { onMounted, watch, computed } from 'vue'
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'

const store = useCounterStore()
const { articleList, loading } = storeToRefs(store)
const isLoggedIn = computed(() => !!localStorage.getItem('token'))

const fetchData = async () => {
  try {
    if (isLoggedIn.value) {
      await store.getArticleList()
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

onMounted(() => {
  fetchData()
})

// 监听 token 变化
watch(
  () => localStorage.getItem('token'),
  (newToken) => {
    if (!newToken) {
      store.removeArticleList()
    }
  }
)
</script>

<template>
  <div class="article-container">
    <h1>文章列表</h1>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="!isLoggedIn" class="unauthorized">请先登录查看内容</div>
    <div v-else-if="articleList.length" class="article-list">
      <div v-for="item in articleList" :key="item.id" class="article-card">
        <h3>{{ item.title }}</h3>
        <p>作者：{{ item.author }}</p>
        <p>内容：{{ item.content }}</p>
      </div>
    </div>
    <div v-else class="no-data">暂无数据</div>
  </div>
</template>

<style scoped>
.article-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.article-list {
  display: grid;
  gap: 20px;
  margin-top: 20px;
}

.article-card {
  padding: 15px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.article-card:hover {
  transform: translateY(-2px);
}

.article-info {
  display: flex;
  gap: 15px;
  color: #666;
  margin-top: 10px;
}

.unauthorized {
  text-align: center;
  padding: 40px;
  background: #f5f5f5;
  border-radius: 8px;
  color: #666;
}

.loading {
  text-align: center;
  color: #2196f3;
}

.no-data {
  text-align: center;
  color: #666;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>
